package com.epam.traning.taskmanager;

import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.epam.traning.taskmanager.adapter.TaskAdapter;
import com.epam.traning.taskmanager.adapter.TaskCursorAdapter;
import com.epam.traning.taskmanager.content.ContentManager;
import com.epam.traning.taskmanager.content.contract.TaskContract;
import com.epam.traning.taskmanager.fragment.MagicFragment;
import com.epam.traning.taskmanager.http.HttpRequestBuilder;
import com.epam.traning.taskmanager.service.HttpService;
import com.epam.traning.taskmanager.xml.AppsHandler;
import com.epam.traning.taskmanager.xml.XmlParser;
import com.epam.traning.taskmanager.xml.XmlParser.IXmlHandler;
import com.epam.traning.taskmanager.xml.bo.App;

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>{

	private static final String FRAGMENT_TAG = "fragment_tag";

	private ListView mListView;
	
	private ProgressBar mProgressBar;
	
	private EditText mEditText;
	
	private Button mCreateButton;
	
	private List<JSONObject> mListTask;
	
	private TaskAdapter mTaskAdapter;

	private BroadcastReceiver mHttpServiceReceiver;
	
	private TaskCursorAdapter taskCursorAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView)findViewById(android.R.id.list);
        mProgressBar = (ProgressBar)findViewById(android.R.id.progress);
        mEditText = (EditText)findViewById(R.id.editText);
        mCreateButton = (Button)findViewById(R.id.createButton);
        mProgressBar.setVisibility(View.VISIBLE);
		try {
			AppsHandler xmlHandler = new AppsHandler();
			XmlParser.getInstance().parse(this, R.raw.apps, xmlHandler);
			List<App> result = xmlHandler.getResult();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
       /* ContentManager.getInstance().getTasks(new ParamCallback<List<JSONObject>>() {
			
			@Override
			public void onSuccess(List<JSONObject> p) {
				mProgressBar.setVisibility(View.GONE);
				mListTask = p;
				mTaskAdapter = new TaskAdapter(MainActivity.this, mListTask);
				mListView.setAdapter(mTaskAdapter);
			}

			@Override
			public void onError(Throwable e) {
				mProgressBar.setVisibility(View.GONE);
				Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			
		});*/
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        MagicFragment magicFragment = new MagicFragment();
        Bundle bundle = new Bundle();
        bundle.putString("text", "la-la-la");
		magicFragment.setArguments(bundle);
		transaction.add(R.id.fragmentContainer, magicFragment, FRAGMENT_TAG);
        transaction.commit();
        mHttpServiceReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(HttpService.ACTION_ON_ERROR)) {
					Toast.makeText(MainActivity.this, intent.getStringExtra(HttpService.EXTRA_KEY_MESSAGE), Toast.LENGTH_SHORT).show();
				} else if (action.equals(HttpService.ACTION_ON_SUCCESS)) {
					
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(HttpService.ACTION_ON_ERROR);
		registerReceiver(mHttpServiceReceiver, filter);
		
		taskCursorAdapter = new TaskCursorAdapter(this, null);
		mListView.setAdapter(taskCursorAdapter);
		getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mHttpServiceReceiver);
	}



	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void onCreateButtonClick(View view) {
    	String text = mEditText.getText().toString();
    	if (text != null && text.trim().length() != 0) {
    		/*if (mListTask == null) {
    			mListTask = new ArrayList<String>();
    		}
    		mListTask.add(0, text);
    		if (mTaskAdapter == null) {
    			//TODO create
    		} else {
    			mTaskAdapter.notifyDataSetChanged();
    		}*/
    		Toast.makeText(this, "Your task is added", Toast.LENGTH_SHORT).show();
    	} else {
    		Toast.makeText(this, "Text is empty", Toast.LENGTH_SHORT).show();    		
    	}
    }
    
    public void onHideFragment(View view) {
    	MagicFragment fragment = (MagicFragment)getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
    	long fId = fragment.getFId();
    	FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    	transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    	transaction.hide(fragment);
    	transaction.commit();
    	view.setVisibility(View.GONE);
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.
    		setMessage("Hello Dialog").
    		setTitle("Dialog Title").
    		setIcon(android.R.drawable.ic_dialog_alert).
    		setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_SHORT).show();
				}
			}).
			setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(MainActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
					}
			}).create().show();
    	
    	
    	showNewStyleNotification();
    	//showOldStyleNotification();
    }

    //todo fix crash
	public void showNewStyleNotification() {
		NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(this);
    	Intent intent = new Intent(this, MainActivity.class);
    	final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    	notificationCompat.addAction(android.R.drawable.stat_sys_upload, "ticker text", pendingIntent);
    	notificationCompat.setAutoCancel(true);
    	notificationCompat.setContentTitle("title");
    	notificationCompat.setContentInfo("Hello world");
    	notificationCompat.setLargeIcon(((BitmapDrawable)getResources().getDrawable(R.drawable.ic_launcher)).getBitmap());
    	notificationCompat.setSmallIcon(R.drawable.ic_action_search);
    	Notification notification = notificationCompat.build();
    	NotificationManager	notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	notificationManager.notify(666, notification);
	}

	public void showOldStyleNotification() {
		NotificationManager	notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	// configure the notification
    	Intent intent = new Intent(this, MainActivity.class);
        final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification(android.R.drawable.stat_sys_upload, "ticker text", System
                .currentTimeMillis());
        notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;
        //notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_progress);
        notification.setLatestEventInfo(this, "Uploading...", "Description", pendingIntent);
        notification.contentIntent = pendingIntent;
	        //notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_menu_save);
        //startForeground(NOTIFICATION_ID, notification);
        notificationManager.notify(666, notification);
	}
    
    public void onVkLogin(View view) {
    	startActivity(new Intent(this, VkLoginActivity.class));
    }
    
    public void onStartService(View view) {
    	Intent intent = new Intent(this, HttpService.class);
    	HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
    	httpRequestBuilder.setType(HttpRequestBuilder.Type.GET);
    	httpRequestBuilder.setUrl(ContentManager.TASKS_URL);
		intent.putExtra(HttpService.HTTP_REQUEST_BUILDER, httpRequestBuilder);
		startService(intent);
    }

    @Override
	public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
		  return new CursorLoader(this, TaskContract.TasksColumns.CONTENT_URI,
                 null, null,
                  null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
		taskCursorAdapter.swapCursor(paramD);		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> paramLoader) {
		taskCursorAdapter.swapCursor(null);		
	}

    
}
